"use strict";

/**
 * 参数收集
 * 检测token,必须位于 params_collector之后
 */

var router = require('koa-router')();
var config = require('../config/index.js');
var appUtils = require('../common/app_utils.js');
var errCodes = require('../common/err_code.js');

var __pathPrefix = '/(man)?api'; // 只有 /api 或 /manapi 需要token_chekcer
console.log('router:' + __pathPrefix);

function * checkToken(next) {
  var token = this.request.inParams.fields.token;
  var checkRes = appUtils.checkToken(token);
  if (checkRes.errCode !== 0) return this.body = checkRes;

  var uid = checkRes.result.uid;
  if (!uid) return this.body = appUtils.ferror(errCodes.E_ARGS_INVALID, 'uid');

  // 如果是 manapi,则 manager=1
  var manager = checkRes.result.manager;
  if (this.request.originalUrl.indexOf('/manapi') === 0 && !manager) {
    return this.body = appUtils.ferror(errCodes.E_PERMISSION_DENY, '调用manapi，但manager !=1');
  }
  this.request.inParams.fields.uid = uid;
  this.request.inParams.fields.manager = manager;
  yield next;
}

router.all('/api/**', checkToken);
router.all('/manapi/**', checkToken);

module.exports = router.routes();


